package com.ybkj.daijia.api.member;

import java.io.IOException;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.shiro.crypto.hash.Sha1Hash;
import org.springframework.core.io.support.PropertiesLoaderUtils;

@Slf4j
public class SecurityUtils {

    /**
     * 检测 token 或者  timestamp 是否为空
     *
     * @param token
     * @param timestamp
     * @return
     */
    public static boolean isBlank(String appKey, String token, String timestamp) {

        return StringUtils.isBlank(appKey) || StringUtils.isBlank(token) || StringUtils
            .isBlank(timestamp);
    }

    /**
     * 生成token
     *
     * @param params
     * @return
     */
    public static String genToken(List<String> params) {

        String securityKey = null;
        try {
            Properties prop = PropertiesLoaderUtils.loadAllProperties("security.properties");
            securityKey = prop.getProperty("securityKey");
        } catch (IOException e) {
            e.printStackTrace();
        }

        params.add(securityKey);

        Collections.sort(params);
        Sha1Hash sha1 = new Sha1Hash(params.toString());

        return sha1.toString().toLowerCase();
    }

    /**
     * 检查时间戳是否有效
     *
     * @param timestamp
     * @return
     */
    public static boolean checkTimestamp(long timestamp) {

        Date paramDate = new Date(timestamp);//客户端传递过来的时间戳
        Date date = new Date();//现在时间

        if (paramDate.after(DateUtils.addMinutes(date, 30))) { //传递的时间在服务器当前时间之后，肯定有问题

            return false;
        } else if (paramDate.before(date)) {
            date = DateUtils.addMinutes(date, -30);//30分钟以前
            if (paramDate.before(date)) { //30分钟以内有效
                return false;
            }
        }

        return true;
    }

    /**
     * 检测token是否正确
     *
     * @param params
     * @param token
     * @return
     */
    public static boolean checkToken(List<String> params, String token) {

        String localtoken = genToken(params);
        log.info("Token:{}", localtoken);
        return localtoken.equals(token);
    }

    public static void main(String[] args) {
        String appKey = "aaabbb";
//		String appKey = "da21e0b8e1924c6c8e91726d9e8ca74b";
//		String time1 = "1567153277593";
//		String phone1 = "17381823824";
        String time1 = "1567155257963";
        String phone1 = "15884147162";
        String sec = "8ad72ece52ba445ba365b75f46ef2a42";
        List<String> list = new LinkedList<>();
        list.add(appKey);
        list.add(time1);
        list.add(phone1);
        list.add(sec);
        Collections.sort(list);
        Sha1Hash sha1 = new Sha1Hash(list.toString());
        System.out.println(sha1.toString().toLowerCase());
    }
}
